package eerbaar.client.internal.ctr.operator;

import eerbaar.client.exp.ExpException;
import eerbaar.client.exp.IExp;
import eerbaar.client.exp.IScope;
import eerbaar.client.exp.IState;
import eerbaar.position.PositionFactory;

class Seq implements IExp {

    private final IExp[] array;

    public Seq(IExp[] array) {

        this.array = array;
    }

    @Override
    public Object calcDestination(IScope scope) {

        return PositionFactory.createPosition(0, 0);
    }

    @Override
    public IScope interpret(IScope inScope) throws ExpException {

        IScope scope = inScope;

        IState state = scope.getState();
        String prop = state.getProperty("seq");
        int seq = 0;
        if (prop != null) {
            seq = Integer.parseInt(prop);
        }

        int i = seq;
        if (i < this.array.length) {

            IExp e = this.array[i];
            scope = e.interpret(scope);
        }

        i++;
        if (i >= this.array.length) {
            i = 0;
        }
        state.setProperty("seq", "" + i);

        state.setFinished(false);

        return scope;
    }

    @Override
    public boolean isInteresting(String elementName) {
        return false;
    }

    @Override
    public void populateValueArea(IScope scope) {
        //
    }

    @Override
    public String toString() {

        String s = "";
        s += "(";
        for (IExp e : this.array) {
            s += e.toString();
            s += " ";
        }
        s += " {seq})";

        return s;
    }

    @Override
    public void updateArea(IScope scope) {
        //
    }

}
